import { CloudOutlined, LogoutOutlined, FolderOutlined, EditOutlined, TableOutlined, FileOutlined, HomeOutlined } from '@ant-design/icons';
import { Layout, FloatButton, theme, Menu, ConfigProvider, Space, Breadcrumb, Tooltip, Table, message } from 'antd';
import { memo, useState, useRef, useEffect, useCallback } from 'react';
import { useParams, useNavigate, useLocation, Outlet } from 'react-router-dom';

import { useTableColumns } from './fields';
import style from './index.module.less';
import { mockFileList } from './mockData';

import { delContent, delExcel, delFolder, delFile } from '@/apis/delete';
import { previewFile } from '@/apis/file';
import { updateFolder } from '@/apis/folder';
import { useMessage } from '@/hooks/useMessage';
import { FILE_STATUS, formatDate } from '@/utils';
import { clearToken } from '@/utils';

import { useDispatch } from 'react-redux';
import { showMessage } from '@/store/modules/message';
import { clearUserInfo } from '@/store/modules/user';
import { MemoAddNewFile } from '@/components/AddNewFile';
import { UploadFile } from '@/components/UploadFile';
import { MemoSearch } from '@/components/Search';
import { getFileList } from '@/apis/fileList';
import { MemoMenu } from '@/components/Menu';
import { ExportDoc } from '@/components/Export';
import { searchDocList, deleteDocByDocIds, searchDocByName } from './api';
import { getDocDetailsByDocId } from '../detail/api';
import { convertTiptapToDocx } from '@/utils/tiptapToDocxConverter';
import { useDocExport } from '@/hooks/useDocExport';
import BulkDeleteDoc from './component/BulkDeleteDoc';

import { debounce } from '@/utils/debounceThrottle';
import { useMemo } from 'react';

// 是否使用模拟数据（前后端分离开关）
const USE_MOCK_DATA = false;
const { Content, Sider } = Layout;
const DocList = () => {
    const {
        token: { colorBgContainer, borderRadiusLG },
    } = theme.useToken();
    const param = useParams()
    const [folderTree, setFolderTree] = useState([])
    const navigate = useNavigate()
    const location = useLocation()
    const [collapsed, setCollapsed] = useState(false);
    const dispatch = useDispatch();
    const { error, contextHolder } = useMessage()
    const [list, setList] = useState([])
    const [loading, setLoading] = useState(true)
    const [isModalOpen, setIsModalOpen] = useState(false)
    const [modalLoding, setModalLoading] = useState(false)
    const [currentFolder, setCurrentFolder] = useState('')
    const folderName = useRef('')
    const [deleteLoading, setDeleteLoading] = useState(false);

    // 添加侧边栏拖拽相关状态
    const [siderWidth, setSiderWidth] = useState(250);
    const [isDragging, setIsDragging] = useState(false);
    const minWidth = 200;
    const maxWidth = 600;
    // 添加导出相关状态
    const [selectedDocs, setSelectedDocs] = useState([]);
    const [exportModalVisible, setExportModalVisible] = useState(false);
    // 使用导出 Hook
    const { exportLoading, handleBatchExport, handleBatchExportToPdf } = useDocExport();
    const exit = () => {
        dispatch(showMessage({ message: '退出成功', type: 'success' }))
        dispatch(clearUserInfo())
        clearToken()
        navigate('/login')
    }

    // 处理拖拽开始
    const handleMouseDown = (e) => {
        e.preventDefault();
        setIsDragging(true);
        document.addEventListener('mousemove', handleMouseMove);
        document.addEventListener('mouseup', handleMouseUp);
    };

    // 处理拖拽中
    const handleMouseMove = (e) => {
        if (!isDragging) return;
        const newWidth = e.clientX;
        const clampedWidth = Math.max(minWidth, Math.min(maxWidth, newWidth));
        setSiderWidth(clampedWidth);
    };

    // 处理拖拽结束
    const handleMouseUp = () => {
        setIsDragging(false);
        document.removeEventListener('mousemove', handleMouseMove);
        document.removeEventListener('mouseup', handleMouseUp);
    };

    // 组件卸载时清理事件监听
    useEffect(() => {
        return () => {
            document.removeEventListener('mousemove', handleMouseMove);
            document.removeEventListener('mouseup', handleMouseUp);
        };
    }, [isDragging]);
    const getList = useCallback(async (id = '') => {
        try {
            setLoading(true)
            if (USE_MOCK_DATA) {
                // 使用模拟数据
                setTimeout(() => {
                    // 如果有id参数，模拟只返回该文件夹下的文件
                    const filteredList = id ?
                        mockFileList.filter(item => item.id !== id) : // 排除当前文件夹
                        mockFileList;
                    setList(filteredList);
                    setLoading(false);
                }, 500); // 添加延迟以模拟网络请求
            } else {
                // 使用真实API - 改为调用searchDocList
                const res = await searchDocList()
                if (res && res.code === 200 && res.data) {
                    const docList = res.data.map(item => ({
                        id: item.docId,
                        name: item.docName,
                        owner: item.username,
                        updateTime: item.updateTime,
                        status: 1
                    }));
                    setList(docList);
                } else {
                    setList([]);
                }
                setLoading(false);
            }
        } catch (e) {
            error({
                content: '数据获取失败'
            })
            setLoading(false)
        }

    }, [])
    const preview = async (id) => {
        try {
            if (USE_MOCK_DATA) {
                // 模拟预览操作
                window.open('https://example.com/preview', '_blank');
            } else {
                // 真实预览操作
                const res = await previewFile(id);
                window.open(res.data, '_blank');
            }
        } catch (e) {
            error({
                content: '下载文件失败，请检查网络'
            });
        }
    };
    const handleSearch = async (value) => {
        if (!value) {
            // 搜索框为空时恢复全部列表
            getList();
            return;
        }
        setLoading(true);
        try {
            const res = await searchDocByName({ name: value });
            if (res && res.code === 200 && res.data) {
                const docList = res.data.map(item => ({
                    id: item.docId,
                    name: item.docName,
                    owner: item.username,
                    updateTime: item.updateTime,
                    status: 1
                }));
                setList(docList);
            } else {
                setList([]);
            }
        } catch (e) {
            setList([]);
        }
        setLoading(false);
    };
    const refreshUrl = () => {
        if (param.id === undefined) navigate(`/home/docList`, { state: { refresh: Date.now() } })
        else navigate(`/home/docList/${param.id}`, { state: { refresh: Date.now() } })
    }
    const handleMenuClick = async (action, record) => {
        if (action === 'details') {
            handleClick(record)
        } else if (action === 'delete') {
            try {
                if (USE_MOCK_DATA) {
                    // 模拟删除操作
                    setLoading(true);
                    setTimeout(() => {
                        // 模拟删除成功
                        setLoading(false);
                        // 刷新列表
                        if (param.id === undefined) getList();
                        else getList(param.id);
                    }, 500);
                } else {
                    // 真实删除操作
                    // 只处理在线文档的删除
                    if (record.status === FILE_STATUS['在线文档']) {
                        await deleteDocByDocIds([record.id]);// 传数组
                    }
                    // 删除后刷新列表
                    if (param.id === undefined) getList();
                    else getList(param.id);
                    setLoading(false);
                    message.success('删除成功');
                }
            } catch (e) {
                message.error('删除失败');
            }

        } else if (action === 'update') {
            setCurrentFolder(record);
            setIsModalOpen(true);
            folderName.current = record.name;
        } else if (action === 'download') {
            if (USE_MOCK_DATA) {
                // 模拟下载/预览操作
                window.open('https://example.com/preview', '_blank');
            } else {
                preview(record.id);
            }
        }
    };

    const handleClick = (record) => {
        if (record.status === FILE_STATUS['在线文档']) {
            navigate(`/docList/docDetail/${record.id}`);
        }
    }

    useEffect(() => {
        if (param.id === undefined) getList()
        else getList(param.id)
    }, [param.id]) // 移除 getList 依赖项，只保留 param.id

    useEffect(() => {
        if (location.state?.refresh)
            if (param.id === undefined) getList()
            else getList(param.id)
    }, [location.state, param.id])
    const { nameColumn, ownerColumn, updateTimeColumn, actionColumn } = useTableColumns(handleMenuClick)
    const columns = [nameColumn, ownerColumn, updateTimeColumn, actionColumn]

    // 修改行选择配置
    const rowSelection = {
        selectedRowKeys: selectedDocs.map(docId => `doc-${docId}`),
        onChange: (selectedRowKeys, selectedRows) => {
            const realDocIds = selectedRows.map(row => row.id);
            setSelectedDocs(realDocIds);
        },
        getCheckboxProps: record => ({
            disabled: record.name === 'Disabled User',
            name: record.name,
        }),
    };

    // 处理Word导出按钮点击
    const onExportClick = async () => {
        try {
            const successCount = await handleBatchExport(selectedDocs);
            if (successCount > 0) {
                setSelectedDocs([]); // 清空选择
            }
        } catch (error) {
            console.error('导出失败:', error);
        }
    };

    //处理PDF导出按钮点击
    const onExportPdfClick = async () => {
        try {
            const successCount = await handleBatchExportToPdf(selectedDocs);
            if (successCount > 0) {
                setSelectedDocs([]); // 清空选择
            }
        } catch (error) {
            console.error('PDF导出失败:', error);
        }
    };


    // 修改表格数据源，使用更安全的key生成方式
    const tableDataSource = list.map(item => ({
        ...item,
        key: `doc-${item.id}`, // 使用更明确的key格式
        updateTime: formatDate(item.updateTime)
    }));
    // 防抖
    const debouncedHandleSearch = useMemo(() => debounce(handleSearch, 300), [handleSearch]);

    return (
        <Layout style={{
            height: '100vh',
        }}>
            {contextHolder}
            <FloatButton
                icon={<LogoutOutlined />}
                type='primary'
                onClick={exit}
                style={{
                    insetInlineEnd: 38,
                    insetBlockEnd: 100 
                }} />
            <div className={style.siderContainer}>
                <Sider
                    width={siderWidth}
                    breakpoint="lg"
                    collapsed={collapsed}
                    onCollapse={setCollapsed}
                    collapsedWidth={80}
                    style={{
                        background: colorBgContainer,
                        overflowY: 'scroll',
                        transition: isDragging ? 'none' : undefined
                    }}
                    className={style.sider}
                >
                    <div className={style.logo}>{collapsed ? <CloudOutlined style={{
                        fontSize: '25px',
                        color: '#1677ff'
                    }} /> : 'CoDoc'}</div>
                    <MemoMenu></MemoMenu>
                </Sider>
                <div
                    className={style.siderResizer}
                    onMouseDown={handleMouseDown}
                />
            </div>
            <Layout
                style={{
                    padding: '0 24px 0',
                }}
            >
                <Content
                    style={{
                        padding: 24,
                        margin: 0,
                        minHeight: 280,
                        background: colorBgContainer,
                        borderRadius: borderRadiusLG,
                    }}
                >
                    <div style={{
                        fontSize: '24px'
                    }}
                        className={style.breadcrumb}>
                        我的文档
                    </div>
                    <ConfigProvider
                        wave={{
                            disabled: true,
                        }}
                    >
                        <Space size={50} style={{
                            marginTop: 20
                        }}>
                            <MemoAddNewFile></MemoAddNewFile>
                            <UploadFile></UploadFile>
                            <ExportDoc
                                selectedDocs={selectedDocs}
                                onExport={onExportClick}
                                onExportPdf={onExportPdfClick}
                                selectedCount={selectedDocs.length}
                                loading={exportLoading}
                            />
                            <BulkDeleteDoc
                                selectedDocs={selectedDocs}
                                selectedCount={selectedDocs.length}
                                loading={deleteLoading}
                                onDelete={async () => {
                                    setDeleteLoading(true);
                                    try {
                                        await deleteDocByDocIds(selectedDocs);
                                        setSelectedDocs([]);
                                        getList();
                                        message.success('删除成功');
                                    } catch (e) {
                                        message.error('删除失败');
                                    }
                                    setDeleteLoading(false);
                                }}
                            />
                            <MemoSearch  onSearch={debouncedHandleSearch} />
                        </Space>
                        <Table
                            rowSelection={Object.assign({ type: 'checkbox' }, rowSelection)}
                            columns={columns}
                            dataSource={tableDataSource}
                            pagination={true}
                            scroll={{ y: 'calc(100vh - 260px)' }}
                            onRow={(record) => ({
                                onClick: () => handleClick(record)
                            })}
                            className={style.fileList}
                        />
                    </ConfigProvider>
                    <div
                        style={{
                            background: colorBgContainer,
                            borderRadius: borderRadiusLG,
                        }}
                        className={style.fileList}
                    >
                        <Outlet></Outlet>
                    </div>
                </Content>
            </Layout>
        </Layout >
    );
}
export const MemoDocList = memo(DocList)